<!--
由于投资人关联了多个相关业务表，特在此进行一点前端部分说明：
0.投资人在自我提交认证申请时，只能对自己id进行申请，申请接口为=
1.投资人由admin端添加时，同时更新到user表和investor表
修改处：1 注册账号必须校验手机号，
      2  公司名称为必填
      3 本页面显示的是已认证的，即authStatus == 2，不包括未认证和认证失败，认证过期的
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyname">
        <el-input
          v-model="queryParams.companyname"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
     
      <el-form-item label="会员类型" prop="memberPriceTemplateId">
         <el-select v-model="queryParams.memberPriceTemplateId" placeholder="请选择会员类型">
            <el-option
              v-for="dict in dict.type.sys_vip_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:investor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:investor:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:investor:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:investor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="investorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="公司名称" align="center" prop="companyname" />
      <!-- <el-table-column label="公司任职" align="center" prop="position" /> -->
      <el-table-column label="vip缴费时间" align="center" prop="chargeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.chargeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员类型" align="center" prop="memberPriceTemplateId" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_vip_type" :value="scope.row.memberPriceTemplateId"/>
        </template>
      </el-table-column>
      
      <el-table-column label="认证状态" align="center" prop="authStatus" >  
        <template slot-scope="scope">
          <dict-tag :options="dict.type.member_auth_status" :value="scope.row.authStatusAll.authStatus"/>
        </template>
      </el-table-column>/>
      <el-table-column label="用户图片" align="center" prop="picsId" >
        <template slot-scope="scope">
        <el-popover placement="top-start" trigger="click">
          <a :href="scope.row.picsId" target="_blank" title="查看图片">
            <img :src="scope.row.picsId" style="width: 500px;height: 400px">
          </a>
          <img slot="reference" :src="scope.row.picsId" style="width: 50px;height: 50px; cursor:pointer">
        </el-popover>
       </template>
      </el-table-column>
     
      <el-table-column label="vip到期时间" align="center" prop="vipendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.vipendTime, '{y}-{m}-{d}') }}</span>
        </template>
      
      </el-table-column>
      <el-table-column label="真实姓名" align="center" prop="realName" />
      <el-table-column label="联系方式" align="center" prop="tel" />
      <el-table-column label="上传资料" align="center" prop="upinfo" >
        <template slot-scope="scope">
        
          <a :href="scope.row.upinfo" target="_blank" title="查看">
            查看
          </a>

       </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:investor:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:investor:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改投资人对话框，开启此对话框才进行对应用户user内容的查询 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="companyname">
          <el-input v-model="form.companyname" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司任职" prop="position">
          <el-input v-model="form.position" placeholder="请输入公司任职" />
        </el-form-item>
        <el-form-item label="vip缴费时间" prop="chargeTime">
          <el-date-picker clearable
            v-model="form.chargeTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择vip缴费时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员类型" prop="memberPriceTemplateId">
           <el-select v-model="form.memberPriceTemplateId" placeholder="请选择会员类型">
            <el-option
              v-for="dict in dict.type.sys_vip_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户登录账号" :disabled="username_disable_flag" />
        </el-form-item>
       
        <el-form-item label="上传照片" prop="picsId">
          <el-upload
                  class="upload-demo"
                  :limit="1"
                  :action="uploadFileUrl"
                  :before-upload="beforeUpload"
                  :on-success="handleUploadSuccess"
                  :data = "updata"
                  :headers="headers"
                  :file-list="fileList"
                  list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">不超过5Mb</div>
          </el-upload>   
        </el-form-item>
        <el-form-item label="案例列表" prop="casesId">
          <el-select v-model="form.caseId" placeholder="案例列表">
            <el-option
              v-for="i in caseList"
              :key="i.id"
              :label="i.caseName"
              :value="i.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值历史" prop="chargeHisId">
          <el-input v-model="form.chargeHisId" placeholder="请输入充值历史" />
        </el-form-item>
        <el-form-item label="vip到期时间" prop="vipendTime">
          <el-date-picker clearable
            v-model="form.vipendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择vip到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入联系方式" />
        </el-form-item>
         <el-form-item label="上传资料" prop="upinfo">
          <el-upload
                  class="upload-demo"
                  :limit="1"
                  :action="uploadFileUrl"
                  :before-upload="beforeUpload2"
                  :before-remove="beforeRemove2"
                  :on-success="handleUploadSuccess2"
                  :data = "updata2"
                  accept=".doc, .docx, .xls, .xlsx, .csv, .pdf, .jpg"
                  :headers="headers"
                  :file-list="fileList2">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">不超过10Mb</div>
          </el-upload>   
        </el-form-item>
      
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInvestor, getInvestor, delInvestor, addInvestor, updateInvestor } from "@/api/system/investor";
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus } from "@/api/system/user";
import { listCase } from "@/api/member/case";
import { getToken } from "@/utils/auth";
export default {
  name: "Investor",
  dicts: ['sys_yes_no', 'sys_vip_type', 'member_auth_status'],
  data() {
    return {
      //////////////////////////////////////////////
      fileList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/uploadFile", // 上传的图片服务器地址
       headers: {
        Authorization: "Bearer " + getToken(),
      },
       uploadObjectUrl: "", // 纯前端预览地址-upload
       uploadOnlineUrl: "", // 后端返回的上传地址-upload
       updata:{"strPath": "pics"},
       ////////////////////////////////////////////
       fileList2: [],
       uploadObjectUrl2: "", // 纯前端预览地址-upload
       uploadOnlineUrl2: "", // 后端返回的上传地址-upload
       updata2:{"strPath": "attachfiles"},

      // 遮罩层
      loading: true,
      caseList: [],
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSysUser: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投资人表格数据
      investorList: [],
      // 用户信息表格数据
      sysUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      username_disable_flag: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyname: null,
        position: null,
        chargeTime: null,
        memberPriceTemplateId: null,
        isSupplier: null,
        isScenespot: null,
        isVip: null,
        sceneId: null,
        supplierId: null,
        userName: null,
        authStatus: null,
        picsId: null,
        casesId: null,
        chargeHisId: null,
        vipendTime: null,
        realName: null,
        tel: null,
        upinfo: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

       companyname: [
         { required: true, message: "公司名称不能为空", trigger: "blur" }
       ],
        userName: [
          { required: true, message: "用户账号不能为空，需要为手机号", trigger: "change" },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'change' }
        ],
        authStatus: [
          { required: true, message: "认证状态不能为空", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" }
        ],
        upinfo: [
          { required: true, message: "上传资料不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!');
        }
        return isJPG && isLt5M;
      },
      beforeUpload2(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;

        if (!isLt10M) {
          this.$message.error('上传大小不能超过 10MB!');
        }
        return isLt10M;
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleUploadSuccess(res, file) {
     // console.log(res.urls);
      this.form.picsId = res.data.url;
    },
    ////////////////////////////////////////
     handleRemove2(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview2(file) {
        console.log(file);
      },
      handleExceed2(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove2(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleUploadSuccess2(res, file) {     
      this.form.upinfo = res.data.url;
    },
    /** 查询投资人列表 */
    getList() {
      this.loading = true;
      listInvestor(this.queryParams).then(response => {
        this.investorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.caseList = [],
      this.form = {
        id: null,
        companyname: null,
        position: null,
        chargeTime: null,
        memberPriceTemplateId: null,
        isSupplier: null,
        isScenespot: null,
        isVip: null,
        sceneId: null,
        supplierId: null,
        userName: null,
        authStatus: null,
        picsId: null,
        casesId: null,
        chargeHisId: null,
        vipendTime: null,
        realName: null,
        tel: null,
        upinfo: null
      };
      this.sysUserList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.username_disable_flag = false;
      this.open = true;
      this.title = "添加投资人";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.username_disable_flag = true;
      const id = row.id || this.ids
      getInvestor(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改投资人";
      });
      let  queryParams =  {
        pageNum: 1,
        pageSize: 1000,
        memberInvestorId: row.id
      };
      let that = this
      listCase(queryParams).then(response => {
        // console.log(response.rows)
        that.caseList = response.rows
      });
    },
    /** 提交按钮 */
    /** 提交时将手机号转为userid*/
    submitForm() {
      let retval = null;
      this.$refs["form"].validate(valid => {
        if (valid) {
  
        if (this.form.id != null) {
          updateInvestor(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
      });
      } else {
          addInvestor(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }

          
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除投资人编号为"' + ids + '"的数据项？').then(function() {
        return delInvestor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 用户信息序号 */
    rowSysUserIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 用户信息添加按钮操作 
    handleAddSysUser() {
      let obj = {};
      obj.deptId = "";
      obj.userName = "";
      obj.nickName = "";
      obj.userType = "";
      obj.email = "";
      obj.phonenumber = "";
      obj.sex = "";
      obj.avatar = "";
      obj.password = "";
      obj.status = "";
      obj.loginIp = "";
      obj.loginDate = "";
      obj.remark = "";
      this.sysUserList.push(obj);
    },*/
    /** 用户信息删除按钮操作 */
    handleDeleteSysUser() {
      if (this.checkedSysUser.length == 0) {
        this.$modal.msgError("请先选择要删除的用户信息数据");
      } else {
        const sysUserList = this.sysUserList;
        const checkedSysUser = this.checkedSysUser;
        this.sysUserList = sysUserList.filter(function(item) {
          return checkedSysUser.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSysUserSelectionChange(selection) {
      this.checkedSysUser = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/investor/export', {
        ...this.queryParams
      }, `investor_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
